/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hazardsource.service.impl;

import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.domain.IndicationType;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hazardsource.mapper.IndicationTypeMapper;
import com.koron.hazardsource.service.api.IndicationItemsService;
import com.koron.hazardsource.util.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class IndicationItemsServiceImpl implements IndicationItemsService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(IndicationItemsServiceImpl.class);

    private static Map<String, IndicationItems> cacheMap = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        try (SessionFactory factory = new SessionFactory()) {
            IndicationItemsMapper mapper = factory.getMapper(IndicationItemsMapper.class);
            List<IndicationItems> items = mapper.queryAll(null, null, null, null);
            if (!items.isEmpty()) {
                cacheMap.putAll(items.stream().collect(Collectors.toMap(IndicationItems::getId, d -> d)));
            }
        }
    }

    @Override
    public MessageBean<Integer> save(IndicationItems bean) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(bean.getName()) || StringUtils.isEmpty(bean.getTypeKey())) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                return msg;
            }
            IndicationType type = factory.getMapper(IndicationTypeMapper.class).queryByKey(bean.getTypeKey());
            if (null == type) {
                msg.setCode(BusinessCode.MESSAGE_CODE_INDICATIONTYPE_NOT_EXISIT);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_INDICATIONTYPE_NOT_EXISIT);
                return msg;
            }
            Integer value = 0;
            if (StringUtils.isEmpty(bean.getId())) {
                //新增
                List<IndicationItems> itemsList = factory.getMapper(IndicationItemsMapper.class).queryAll(bean.getTypeKey(), bean.getName(), null, null);
                if (itemsList.size() > 0) {
                    msg.setCode(BusinessCode.MESSAGE_CODE_INDICATIONITEMS_DOUBLE_NAME);
                    msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_INDICATIONITEMS_DOUBLE_NAME);
                    return msg;
                }
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                value = factory.getMapper(IndicationItemsMapper.class).insert(bean);
            } else {
                //修改
                if (factory.getMapper(IndicationItemsMapper.class).isExistByNameAndTypeKey(bean.getId(), bean.getName(),
                        bean.getTypeKey()) > 0) {
                    msg.setCode(BusinessCode.MESSAGE_CODE_INDICATIONITEMS_DOUBLE_NAME);
                    msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_INDICATIONITEMS_DOUBLE_NAME);
                    return msg;
                }
                value = factory.getMapper(IndicationItemsMapper.class).update(bean);
            }
            if (value > 0) {
                cacheMap.put(bean.getId(), bean);
                msg.setCode(BusinessCode.MESSAGE_CODE_SUCCESS);
                msg.setDescription("保存成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.MESSAGE_CODE_FAIL);
                msg.setDescription("保存失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> batchDelete(List<String> idList) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null == idList || idList.size() <= 0) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                return msg;
            }
            List<String> delIdList = new ArrayList<>();
            for (String id : idList) {
                IndicationItems items = queryOne(id).getData();
                if (null != items && items.getReferenceCount() == 0) {
                    delIdList.add(id);
                }
            }
            if (null == delIdList || delIdList.size() <= 0) {
                msg.setCode(BusinessCode.MESSAGE_CODE_INDICATIONITEMS_IS_REFRENCED);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_INDICATIONITEMS_IS_REFRENCED);
                return msg;
            }
            Integer value = factory.getMapper(IndicationItemsMapper.class).batchDetele(delIdList);
            if (value > 0) {
                delIdList.stream().forEach(id -> cacheMap.remove(id));
                msg.setCode(BusinessCode.MESSAGE_CODE_SUCCESS);
                msg.setDescription("删除成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.MESSAGE_CODE_FAIL);
                msg.setDescription("删除失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
    }

    @Override
    public MessageBean<IndicationItems> queryOne(String id) {
        MessageBean<IndicationItems> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                return msg;
            }
            IndicationItems items = factory.getMapper(IndicationItemsMapper.class).queryOne(id);
            msg.setCode(BusinessCode.MESSAGE_CODE_SUCCESS);
            msg.setDescription("获取指标项详情成功");
            msg.setData(items);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<IndicationItems>> queryByCondition(String typeKey, String name, Integer start, Integer rows) {
        MessageBean<DataBean<IndicationItems>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<IndicationItems> list = factory.getMapper(IndicationItemsMapper.class).queryAll(typeKey, name, start, rows);
            Integer totalNumber = factory.getMapper(IndicationItemsMapper.class).countAll(typeKey, name);
            rows = rows == null || rows <= 0 ? 1 : rows;
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<IndicationItems> dataBean = new DataBean<>();
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setList(list);
            msg.setCode(BusinessCode.MESSAGE_CODE_SUCCESS);
            msg.setDescription("查询指标项列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
    }

    @Override
    public IndicationItems matchItems(String typeName, String itemName) {
        try(SessionFactory factory=new SessionFactory()){
            IndicationItems items=factory.getMapper(IndicationItemsMapper.class).matchIndicationItems(typeName,itemName);
            return items;
        }
    }


    @Override
    public Map<String, IndicationItems> getCacheMap() {
        return cacheMap;
    }

}
